function [outSt,logL]=kfilterNSplits(parvec,funcmod,Y,trainvec,solveopt,addsol)
% ====================================================================
% ====================================================================
%% 1. Model solution
% Matrices of second sample stored in structure second 
[G,R,C,eu,SDX,Z,structOne,ssvec,structTwo]=feval(funcmod,parvec,solveopt,addsol);
if isequal(eu,[1;1])==0 
    error('Model is not determinate') 
end 
[T,ny]=size(Y);
Y=Y';
if length(addsol.tauVec)~=T 
    warning('Addsol is Longer than T'); 
    quer('c'); 
end 
%% 3. Forward filter 
% 3.1. Dimensions and storage 
ns = size(G,1); 
nx = size(SDX,1); 

vt=zeros(ny,T);
finvt=zeros(ny,ny,T);
kpartg=zeros(ns,ny,T);
logLnc=zeros(T,1); 
yfor =zeros(ny,T);

% Matrices with one additional entry (initialization)
% to recover observables 
stt=zeros(ns,T+1);
ptt=zeros(ns,ns,T+1);

W          = eye(ny);
Zdim       = zeros(T,1); 
mat_obspos = zeros(T,ny);

% 3.2 Initialization 
stt(:,1) = zeros(ns,1); 
P0 = lyapunov_symm(G(:,:,addsol.tauVec(1)),...
    R(:,:,addsol.tauVec(1))*(SDX(:,:,addsol.tauVec(1))')...
    *SDX(:,:,addsol.tauVec(1))*(R(:,:,addsol.tauVec(1))'));
ptt(:,:,1) = P0;

% 3.3 Start Forward Filter using KF_DK 
for ii=1:T;
    
    % Handling of missing observations
    ytt=Y(:,ii);
    
    % Determine W and position of the NAN
    ind =~isnan(ytt);
    rowt =find(~isnan(ytt));
    
    
    ytt=ytt(ind);
    Zdim(ii)=length(ytt);
    Ztt=W((ind==1),:)*Z(:,:,addsol.tauVec(ii));
    mat_obspos(ii,1:Zdim(ii))=rowt;
    dimt=( 1:Zdim(ii) );
    %% Demeaning is done here 
    ytt = ytt - Ztt*C(:,addsol.tauVec(ii));
    
%     if addsol.tauVec(ii)==2 
%         disp('Here'); 
%     end 
    
    yfor(dimt,ii) =Ztt*(G(:,:,addsol.tauVec(ii))*stt(:,ii) + C(:,addsol.tauVec(ii)));
    
    [stt(:,ii+1),ptt(:,:,ii+1),logLnc(ii),vt(dimt,ii),finvt(dimt,dimt,ii),...
        kpartg(:,dimt,ii)]=feval(@kf_dk,ytt,Ztt,...%Z(:,:,addsol.tauVec(ii)),...
        stt(:,ii),ptt(:,:,ii),G(:,:,addsol.tauVec(ii)),...
        R(:,:,addsol.tauVec(ii))*(SDX(:,:,addsol.tauVec(ii))'));
end

%% 4. Likelihood with Integration Constant  
outSt.logLncFull=logLnc; 

logLnc=logLnc(trainvec(1):trainvec(2)); 
logL=-0.5*sum(Zdim)*log(2*pi)+sum(logLnc);

%% 5. Truncate filters and obtain initial observations 
yferr=vt';
yfor =yfor'; 
stt=stt(:,2:end); ptt=ptt(:,:,2:end); 

%% 6. Disturbance smoother with TV matrices 
% Obtain the Innovations using a disturbance smoother 
etamat=zeros(nx,T); 
smooth_st=zeros(ns,T); 
rmat=zeros(ns,T); 

%% 6.1 Initialize RSTAR & start at t=Nobs 
rstar=zeros(ns,1); 
[rstar,etamat(:,end)]=smoothdis(rstar,...
    (SDX(:,:,addsol.tauVec(end))')*SDX(:,:,addsol.tauVec(end)),R(:,:,addsol.tauVec(end))',...
    Ztt',...%Z(dimt,:,addsol.tauVec(end))',...
    finvt(dimt,dimt,end),zeros(ns),vt(dimt,end));
smooth_st(:,end)=stt(:,end)+ptt(:,:,end)*rstar; 
rmat(:,end)=rstar; 

%% 6.2 Begin Backward recursion 
for ii=(T-1):-1:1;
    
    % Varying dimension in the backward recurions
    dimt=( 1:Zdim(ii) );
    % [Ztt]'= [Wtt*Z]' = = Z'*Wtt'
    Ztt = (Z(:,:,addsol.tauVec(ii))')*( W( mat_obspos(ii,1:Zdim(ii)),:)');
    
    [rstar,etamat(:,ii)]=smoothdis(rstar,...
        (SDX(:,:,addsol.tauVec(ii))')*SDX(:,:,addsol.tauVec(ii)),...
        R(:,:,addsol.tauVec(ii))',Ztt,finvt(dimt,dimt,ii),...
        ((G(:,:,addsol.tauVec(ii+1))-G(:,:,addsol.tauVec(ii+1))*...
        kpartg(:,dimt,ii)*Ztt')'),vt(dimt,ii));
    smooth_st(:,ii)=stt(:,ii)+ptt(:,:,ii)*rstar;
    rmat(:,ii)=rstar; 
end
a0 = P0*G(:,:,addsol.tauVec(1))'*rstar;   % Note: this is only correct in the case where a0 = zeros(ns,1) 
etamat=(etamat)';
smooth_st=(smooth_st)'; 
stt  =stt'; 


%% 7. Check Smoother 
% Check that Smooth States are identical if using disturbance smoother (above) vs. state smoother (below) 
% and if can also recover the observables
tol=1e-5; 
% State at time zero give by GG1*azero+Pzero*rstar;
[yCheck,smoothCheck]=kfilterRegSplitSimulation(a0,etamat'); 
disp('Max Discrepancy Smooth vs. Actual Data'); 
Ydem=zeros(ny,T); 
for ii=1:T 
    Ydem(:,ii)=Y(:,ii)- Z(:,:,addsol.tauVec(ii))*C(:,addsol.tauVec(ii));
end 
maxdifY=comparemat(yCheck,Ydem'); 
disp('Max Discrepancy State and Innovation Smoother'); 
maxdifS=comparemat(smoothCheck,smooth_st); 
if maxdifY > tol || maxdifS > tol 
    error('Smoother discrepancy exceeds tolerance') 
end 

%% 8. Initial Variance and State per shock (used below for the counterfactual decompositions)
% vInitialPershock: Initial Variance, decomposed per shock 
% sOnePerShock, State at time 1 decomposed, decomposed per shock
vInitialPerShock=zeros(ns,ns,nx);
sZeroSmoothPerShock=zeros(ns,nx); 
sOneSmoothPerShock =zeros(ns,nx); 
for ii=1:nx
    vInitialPerShock(:,:,ii)=lyapunov_symm(G(:,:,addsol.tauVec(1)),...
        R(:,ii,addsol.tauVec(1))*SDX(ii,ii,addsol.tauVec(1))*...
        SDX(ii,ii,addsol.tauVec(1))*(R(:,ii,addsol.tauVec(1))'));
    sZeroSmoothPerShock(:,ii) = vInitialPerShock(:,:,ii)*G(:,:,addsol.tauVec(1))'*rstar;
    etatemp = zeros(nx,1);
    etatemp(ii) = etamat(1,ii);
    sOneSmoothPerShock(:,ii)=G(:,:,addsol.tauVec(1))*sZeroSmoothPerShock(:,ii)...
        +R(:,:,addsol.tauVec(1))*etatemp;
end
maxdifSzero=comparemat(sum(sZeroSmoothPerShock,2),a0); 
maxdifSone =comparemat(sum(sOneSmoothPerShock,2),smooth_st(1,:)' ); 
if maxdifSzero > tol; error('Cannot decompose sZeroPerShock'); end 
if maxdifSone > tol; error('Cannot decompose sOnePerShock'); end


%% 9. Counterfactual Decomposition 
% Generate states by feeding each shock at a time, ensure that it recovers
% the original state 
disp('Begin Counterfactual')
countStates=zeros(T,ns,nx);
countObs   =zeros(T,ny,nx);
for ii=1:nx 
    etaTemp=zeros(T,nx); 
    etaTemp(:,ii)=etamat(:,ii); 
    [countObs(:,:,ii),countStates(:,:,ii)]=kfilterRegSplitSimulation(sZeroSmoothPerShock(:,ii),etaTemp');
end 
disp('Maximum Discrepancy Counterfactual States and Smooth States') 
maxdifCount=comparemat(sum(countStates,3),smooth_st); 
if maxdifCount > tol; error('Counterfactual States do not recover smooth states'); end 

% Use this to debug testlikelInitial.m 
outSt.sttNoInitial=stt; 
outSt.pttNoInitial=ptt; 
outSt.filteredSt=stt; 
outSt.aLast=stt(end,:)'; 
outSt.pLast=ptt(:,:,end); 

outSt.smoothSt=smooth_st; 
outSt.innovations=etamat; 
outSt.countSt=countStates; 
outSt.countObs=countObs; 
outSt.decompInitialSt=sOneSmoothPerShock; 
outSt.forecastObs=yfor; 
outSt.aZero=a0; 


%% Subroutine kfilterRegSplitSimulation allows to simulate the model  
% Inputs 
% sInitial: [ns 1] Initial State 
% innovMat: [nx T] matrix of innovations 
% By being a sub-routine it has access to all variables defined above 
% Be-careful not to use an index (ii,jj) used above or to repeat variable
% names
    function [ySim,sSim]=kfilterRegSplitSimulation(sInitial,innovMat) 
        if ~isequal(size(innovMat),[nx T]) 
            error('Input innovMat must be [nx T]') 
        end 
        sSim=zeros(ns,T);
        ySim=zeros(size(Y));
        sSim(:,1)=G(:,:,addsol.tauVec(1))*sInitial + ...
            R(:,:,addsol.tauVec(1))*innovMat(:,1);
        ySim(:,1)=Z(:,:,addsol.tauVec(1))*sSim(:,1); %+C(:,addsol.tauVec(1)));
        for kk=2:T;
            sSim(:,kk)=G(:,:,addsol.tauVec(kk))*sSim(:,kk-1)+...
                R(:,:,addsol.tauVec(kk))*innovMat(:,kk);
            ySim(:,kk)=Z(:,:,addsol.tauVec(kk))*sSim(:,kk); %+C(:,addsol.tauVec(kk)));
        end
        ySim=ySim'; 
        sSim=sSim'; 
    end
%% End of File
end 